<template>
  <div class="search-suggest">
    <van-cell-group>
      <van-cell
        icon="search"
        v-for="(item, index) in searchSuggestionData"
        :key="index"
        @click="$emit('search', item)"
      >
      <div slot="title" v-html="hightLight(item)"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>
 
<script>
import { searchSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  props:  {
    value: {
      type : String,
      default: () => {
        return ''
      },

    }
  },
  data() {
    return {
      searchSuggestionData: [],
    }
  },
  methods: {
    // 获取联想建议（自动补全）
    async getSuggestion() {
      if (this.value) {
        const { data: res } = await searchSuggestion(this.value)

        console.log(res)

        this.searchSuggestionData = res.data.options
      }
    },

    //高亮显示搜索内容
    hightLight(str){

        var reg = new RegExp(this.value, 'gi' )

        return str.replace(reg, `<span style="color:red">${this.value}</span>`)
    }
  },
  // 监听 value
  watch: {
    value: {
      handler: debounce(function (newValue, oldValue) {
        console.log('1111');  
        
        this.getSuggestion()
      }, 300),
       immediate : true // 值发生改变立即执行
    },
  },
}
</script>

<style>
</style>